import { AuthManager } from "../../utils/auth"
import { memberApi, userApi } from "../../utils/api"

// login.ts
Component({
  data: {
    username: '',
    password: '',
    countdown: 0,
    timer: null as any
  },

  lifetimes: {
    detached() {
      // 清理逻辑
    }
  },

  methods: {
    onUsernameInput(e: any) {
      this.setData({ username: e.detail.value })
    },

    onPasswordInput(e: any) {
      this.setData({ password: e.detail.value })
    },



    // 登录
    async login() {
      if (!this.validateUsername() || !this.validatePassword()) {
        return
      }

      // 模拟登录请求
      wx.showLoading({ title: '登录中...' })
      
      const response = await memberApi.login(this.data.username, this.data.password)
      console.log('login response', response)

      if (response.code === 200) {
        AuthManager.saveLoginInfo(response.data)
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          complete: () => {
            wx.switchTab({
              url: '/pages/index/index'
            })
          }
        })
      } else {
        throw new Error(response.message)
      }
    },

    validateUsername() {
      if (!this.data.username) {
        wx.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return false
      }
      if (this.data.username.length < 3 || this.data.username.length > 20) {
        wx.showToast({
          title: '用户名长度3-20位',
          icon: 'none'
        })
        return false
      }
      if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(this.data.username)) {
        wx.showToast({
          title: '用户名只能包含字母、数字、下划线和中文',
          icon: 'none'
        })
        return false
      }
      return true
    },

    validatePassword() {
      if (!this.data.password || this.data.password.length < 6) {
        wx.showToast({
          title: '密码至少6位',
          icon: 'none'
        })
        return false
      }
      return true
    },

    showUserAgreement() {
      wx.showModal({
        title: '用户协议',
        content: '美丽沙龙用户协议内容...',
        showCancel: false
      })
    },

    showPrivacyPolicy() {
      wx.showModal({
        title: '隐私政策',
        content: '美丽沙龙隐私政策内容...',
        showCancel: false
      })
    }
  },
})